package com.xjm.api.web;

import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xjm.entity.model.ProductsModel;
import com.xjm.entity.model.ThemeProductsModel;
import com.xjm.entity.model.ThemesModel;
import com.xjm.entity.vo.Result;
import com.xjm.service.IProductsService;
import com.xjm.service.IThemeProductsService;
import com.xjm.service.IThemesService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xjm
 * @since 2025-02-28
 */
@RestController
@RequestMapping("/user/theme")
@RequiredArgsConstructor
public class WebThemesController {
    private final IThemesService themesService;
    private final IProductsService productsService;
    private final IThemeProductsService themeProductsService;


    @GetMapping
    public Result<List<ThemesModel>> list() {
        return Result.success(themesService.list());
    }

    @GetMapping("/{id}")
    public Result<JSON> getById(@PathVariable Long id) {
        JSON result = new JSONObject();
        ThemesModel themesModel = themesService.getOne(new LambdaQueryWrapper<ThemesModel>().eq(ThemesModel::getId, id).eq(ThemesModel::getStatus, 1));
        if (themesModel == null) return Result.error("该主题不存在");
        result.putByPath("theme", themesModel);
        List<ThemeProductsModel> list = themeProductsService.list(new LambdaQueryWrapper<ThemeProductsModel>().eq(ThemeProductsModel::getThemeId, id));
        List<ProductsModel> productsModels = new ArrayList<>();
        for (ThemeProductsModel themeProductsModel : list) {
            productsModels.add(productsService.getById(themeProductsModel.getProductId()));
        }
        result.putByPath("products", productsModels);
        return Result.success(result);
    }
}
